/**
 * 媒体上传组件
 * Media Uploader Component
 */

class MediaUploader {
  constructor(options = {}) {
    this.options = {
      maxImageSize: 5 * 1024 * 1024, // 5MB
      maxVideoSize: 50 * 1024 * 1024, // 50MB
      maxAudioSize: 10 * 1024 * 1024, // 10MB
      allowedImageTypes: ['image/jpeg', 'image/png', 'image/webp'],
      allowedVideoTypes: ['video/mp4', 'video/webm'],
      allowedAudioTypes: ['audio/mp3', 'audio/wav', 'audio/mpeg'],
      uploadEndpoint: '/api/files/upload',
      ...options
    };
    
    this.uploadQueue = [];
    this.isUploading = false;
  }

  /**
   * 验证文件类型和大小
   */
  validateFile(file) {
    const errors = [];
    
    // 检查文件类型
    const isImage = this.options.allowedImageTypes.includes(file.type);
    const isVideo = this.options.allowedVideoTypes.includes(file.type);
    const isAudio = this.options.allowedAudioTypes.includes(file.type);
    
    if (!isImage && !isVideo && !isAudio) {
      errors.push(`不支持的文件类型: ${file.type}`);
      return { valid: false, errors, type: null };
    }
    
    // 检查文件大小
    let maxSize;
    let type;
    
    if (isImage) {
      maxSize = this.options.maxImageSize;
      type = 'image';
    } else if (isVideo) {
      maxSize = this.options.maxVideoSize;
      type = 'video';
    } else if (isAudio) {
      maxSize = this.options.maxAudioSize;
      type = 'audio';
    }
    
    if (file.size > maxSize) {
      const maxSizeMB = Math.round(maxSize / (1024 * 1024));
      errors.push(`文件大小超出限制 (最大 ${maxSizeMB}MB)`);
      return { valid: false, errors, type };
    }
    
    return { valid: true, errors: [], type };
  }

  /**
   * 上传单个文件
   */
  async uploadFile(file, onProgress = null) {
    const validation = this.validateFile(file);
    if (!validation.valid) {
      throw new Error(validation.errors.join(', '));
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', validation.type);

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      // 上传进度
      if (onProgress) {
        xhr.upload.addEventListener('progress', (e) => {
          if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            onProgress(percentComplete);
          }
        });
      }
      
      // 上传完成
      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
              resolve({
                ...response.file,
                type: validation.type,
                originalFile: file
              });
            } else {
              reject(new Error(response.message || '上传失败'));
            }
          } catch (error) {
            reject(new Error('解析响应失败'));
          }
        } else {
          reject(new Error(`上传失败: HTTP ${xhr.status}`));
        }
      });
      
      // 上传错误
      xhr.addEventListener('error', () => {
        reject(new Error('网络错误'));
      });
      
      // 上传中止
      xhr.addEventListener('abort', () => {
        reject(new Error('上传被中止'));
      });
      
      xhr.open('POST', this.options.uploadEndpoint);
      
      // 添加认证头
      const token = localStorage.getItem('token');
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      }
      
      xhr.send(formData);
    });
  }

  /**
   * 批量上传文件
   */
  async uploadFiles(files, onProgress = null, onFileComplete = null) {
    const results = [];
    const totalFiles = files.length;
    let completedFiles = 0;
    
    for (const file of files) {
      try {
        const result = await this.uploadFile(file, (progress) => {
          if (onProgress) {
            const overallProgress = ((completedFiles + progress / 100) / totalFiles) * 100;
            onProgress(overallProgress, file, progress);
          }
        });
        
        results.push({ success: true, file: result });
        completedFiles++;
        
        if (onFileComplete) {
          onFileComplete(result, null);
        }
        
      } catch (error) {
        results.push({ success: false, error: error.message, fileName: file.name });
        completedFiles++;
        
        if (onFileComplete) {
          onFileComplete(null, error);
        }
      }
    }
    
    return results;
  }

  /**
   * 创建图片预览
   */
  createImagePreview(file) {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve(e.target.result);
      };
      reader.readAsDataURL(file);
    });
  }

  /**
   * 压缩图片
   */
  async compressImage(file, maxWidth = 1920, maxHeight = 1080, quality = 0.8) {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      
      img.onload = () => {
        // 计算新尺寸
        let { width, height } = img;
        
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height);
          width *= ratio;
          height *= ratio;
        }
        
        canvas.width = width;
        canvas.height = height;
        
        // 绘制压缩后的图片
        ctx.drawImage(img, 0, 0, width, height);
        
        // 转换为Blob
        canvas.toBlob((blob) => {
          // 创建新的File对象
          const compressedFile = new File([blob], file.name, {
            type: 'image/webp',
            lastModified: Date.now()
          });
          resolve(compressedFile);
        }, 'image/webp', quality);
      };
      
      img.src = URL.createObjectURL(file);
    });
  }

  /**
   * 获取视频缩略图
   */
  async getVideoThumbnail(file) {
    return new Promise((resolve, reject) => {
      const video = document.createElement('video');
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      video.addEventListener('loadedmetadata', () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        video.currentTime = 1; // 获取第1秒的帧
      });
      
      video.addEventListener('seeked', () => {
        ctx.drawImage(video, 0, 0);
        canvas.toBlob((blob) => {
          const thumbnailFile = new File([blob], `${file.name}_thumb.webp`, {
            type: 'image/webp',
            lastModified: Date.now()
          });
          resolve(thumbnailFile);
        }, 'image/webp', 0.8);
      });
      
      video.addEventListener('error', reject);
      
      video.src = URL.createObjectURL(file);
      video.load();
    });
  }

  /**
   * 获取音频时长
   */
  async getAudioDuration(file) {
    return new Promise((resolve, reject) => {
      const audio = document.createElement('audio');
      
      audio.addEventListener('loadedmetadata', () => {
        resolve(audio.duration);
      });
      
      audio.addEventListener('error', reject);
      
      audio.src = URL.createObjectURL(file);
      audio.load();
    });
  }

  /**
   * 创建上传进度UI
   */
  createProgressUI(fileName) {
    const progressContainer = document.createElement('div');
    progressContainer.className = 'upload-progress bg-white border border-neutral-200 rounded-lg p-4 mb-2 shadow-sm';
    
    progressContainer.innerHTML = `
      <div class="flex items-center justify-between mb-2">
        <span class="text-sm font-medium text-neutral-700 truncate">${fileName}</span>
        <button class="cancel-upload text-neutral-400 hover:text-red-500">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <div class="w-full bg-neutral-200 rounded-full h-2">
        <div class="progress-bar bg-primary h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
      </div>
      <div class="flex items-center justify-between mt-2 text-xs text-neutral-500">
        <span class="progress-text">准备上传...</span>
        <span class="progress-percent">0%</span>
      </div>
    `;
    
    return progressContainer;
  }

  /**
   * 更新进度UI
   */
  updateProgressUI(progressContainer, progress, status = '') {
    const progressBar = progressContainer.querySelector('.progress-bar');
    const progressText = progressContainer.querySelector('.progress-text');
    const progressPercent = progressContainer.querySelector('.progress-percent');
    
    progressBar.style.width = `${progress}%`;
    progressPercent.textContent = `${Math.round(progress)}%`;
    
    if (status) {
      progressText.textContent = status;
    }
    
    if (progress >= 100) {
      progressBar.classList.remove('bg-primary');
      progressBar.classList.add('bg-green-500');
      progressText.textContent = '上传完成';
    }
  }

  /**
   * 移除进度UI
   */
  removeProgressUI(progressContainer, delay = 2000) {
    setTimeout(() => {
      if (progressContainer.parentNode) {
        progressContainer.parentNode.removeChild(progressContainer);
      }
    }, delay);
  }
}

// 导出媒体上传器
window.MediaUploader = MediaUploader;